<?php

namespace App\Http\Controllers;

use SnappyImage;
use QrCode;
use Auth;
use App\Models\User;
use App\Models\UserPromoteRecord;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Overtrue\EasySms\EasySms;

class UserController extends Controller
{
    public function create()
    {
        if(Auth::check())
        {
            return redirect()->route('recharge.index');
        } else {
            return view(isMobile() . 'user.login');
        }
    }

    public function verifiCode(Request $request, EasySms $easysms)
    {

        if($request->ajax()) {
            //发送验证码
            if($request->sendVerificode) {

                //如果已经存在验证码，先删除老的验证码
                if($request->verification_key) {
                    $verification_key = $request->verification_key;
                    \Cache::forget($verification_key);
                }

                $cellphone = $request->cellphone;

                if($request->country == 'cn') {
                    $template = config('easysms.gateways.aliyun.templates.register');
                    $aliyun_cellphone = $request->cellphone;
                } else {
                    $template = config('easysms.gateways.aliyun_th.templates.register');
                    $aliyun_cellphone = '66'.substr($request->cellphone,1);
                }

                $code = str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT);

                if(env('APP_ENV') != 'local') {
                    try{
                        $request = $easysms->send($aliyun_cellphone, [
                            'template' => $template,
                            'data' => [
                                'code' => $code
                            ],
                        ]);
                    } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {
                        $message = $exception->getException('aliyun')->getMessage();
                        dd($message);
                        // session()->flash('danger', '很抱歉，您的邮箱和密码不匹配');
                        // return back()->withErrors([$message]);
                        // abort(500, $message ?: '短信发送异常');
                    }
                }

                $key = 'verificationCode_'.Str::random(15);

                $expiredAt = now()->addMinutes(5);

                //缓存验证码5分钟过期(->toDateTimeString())。
                \Cache::put($key, ['cellphone' => $cellphone, 'verification_code' => $code, 'verification_key' => $key, 'verification_created_at' => Carbon::now()], $expiredAt);

                return response()->json(['verification_key' => $key , 'cellphone' => $cellphone]);
            }

            //验证验证码，通过则注册新用户或者登陆
            if($request->verificode) {

                $cellphone = $request->cellphone;

                $verification_key = $request->verification_key;

                //从缓存获取登录验证信息
                $verifArray = \Cache::get($verification_key);

                if($verifArray === null) {
                    // 自定义错误，验证码失效
                    return response()->json(['error' => 'code402']);
                }

                if($request->verificode_num == $verifArray['verification_code']) {

                    \Cache::forget($verification_key);

                    //判断用户是否存在，存在就登录，不存在就注册
                    $user = User::where('cellphone', $verifArray['cellphone'])->first();

                    if ($user) {
                        Auth::login($user, $request->token);
                        // return redirect()->intended($fallback);
                        return response()->json(['info' => 'login']);
                    } else {
                        $leasted_user_id = User::orderBy('created_at', 'desc')->first();

                        if($leasted_user_id === null) {
                            $leasted_user_id = 1;
                        } else {
                             $leasted_user_id = $leasted_user_id->id + 1;
                        }

                        $user = User::create([
                            'cellphone'         => $verifArray['cellphone'],
                            'name'              => '用户' . $leasted_user_id,
                            'promote_user_id'   => $request->promote_user_id
                        ]);

                        if($request->promote_user_id)
                        {
                            //更新用户积分
                            $add_credit_user = User::find($request->promote_user_id);

                            //id 1 就是推广充值
                            $add_credit_detail = \DB::table('promote_types')->where('id',1)->first();

                            $origin_score = $add_credit_user->credit_score;

                            $origin_total_score = $add_credit_user->total_credit_score;

                            $add_credit_user->update([
                                'credit_score' => $origin_score + $add_credit_detail->score,
                                'total_credit_score' => $origin_total_score + $add_credit_detail->score,
                            ]);

                            //更新积分记录
                            UserPromoteRecord::create([
                                'user_id' => $request->promote_user_id,
                                'promote_desc' => $add_credit_detail->desc,
                                'promote_type' => $add_credit_detail->type,
                                'promote_score' => $add_credit_detail->score,
                            ]);
                        }

                        Auth::login($user, $request->token);
                        return response()->json(['info' => 'creat']);
                    }

                } else {
                    // 自定义错误，验证码错误
                    return response()->json(['error' => 'code401']);
                }
            }
        }
    }

    public function checkResendTime(Request $request) {

        $checkKey = $request->checkkey;

        $verifArray = \Cache::get($checkKey);

        if($verifArray !== null) {
            $exptime = 60 - Carbon::now()->diffInSeconds($verifArray['verification_created_at']);
        } else {
            $exptime = 0;
        }

        return response()->json(['reminde_time' => $exptime, 'cellphone' => $verifArray['cellphone'], 'verification_key' => $verifArray['verification_key']]);
    }

    public function logout()
    {
        Auth::logout();

        return redirect()->route('recharge.index');
    }



    public function wxLogin(Request $request) {

        session(['target_url' => \URL::previous()]);

        $home_url = env('APP_URL');

        $app = \EasyWeChat::OfficialAccount();

        $response = $app->oauth->scopes(['snsapi_userinfo'])->redirect($home_url.'/weixin/loginCallback?uid='.$request->cookie('promote_user_id'));

        return $response;
    }

    public function wxLoginCallback(Request $request) {

        // if (session('target_url') == null) {
        //     $target_url = '/user';
        // } else {
        //     $target_url = session('target_url');
        // }

        // $user->update([
        //     'user_dzone_bg' => $request->userSelect,
        // ]);

        $app = \EasyWeChat::OfficialAccount();

        $wx_user = $app->oauth->user()->toArray();

        $user = Auth::user();

        // 未登录
        // 这里要判断一下用户是不是点击了测试题或者别的需要马上登陆的请求链接，如果是，Authenticate.php 会有一个session在用户登录以后直接跳转
        // 但是这个链接点击一次以后要销毁掉，不然下次登录还会自动定向到那个页面，体验不好
        if ($user->wx_open_id) {
            return redirect()->route('recharge.index');
        } else {
            $user->update([
                'wx_open_id' => $wx_user['id'],
                'nickname' => $wx_user['nickname'],
                'avatar' => $wx_user['avatar'],
                'promote_user_id' => $request->uid,
                'wx_access_token' => $wx_user['token']
            ]);

            if($user->update()) {
                return redirect()->route('recharge.index');
            }
        }

    }

    public function getCreditImg() {

        $qrcode = QrCode::size(300)
                    ->margin(0)
                    ->generate(env('APP_URL').'/recharge?pid='.Auth::id());

        $path = 'uploads/credit/recharge/'.Auth::id().'.jpg';

        $file = env('APP_URL').'/'.$path;
        //get_headers 获取的是请求状态数组，下标0就是http状态，格式：HTTP/1.1 200 OK，所以截取后判断
        $statusCode = substr(get_headers($file)[0], 9, 3);

        if($statusCode == 200) {
            return response()->json(['path'=>$file]);
        } else {
            SnappyImage::loadHtml('<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><style>.template {position: relative;}.template-qrcode {position: absolute;bottom: 100px; right:90px;}.template-qrcode {border: 10px solid #fff;}</style></head><body><div class="template"><div class="template-img"><img src="'.env('APP_URL').'/assets/mobile/images/credit_02.jpg"  width="100%"></div><div class="template-qrcode">'.$qrcode.'</div></div></body></html>')
                ->setOption('width', 1200)
                ->save($path);

            return response()->json(['path'=>'/'.$path.'?'.time()]);
        }
    }
}
